<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2023/12/12
 * Time: 15:38
 */

namespace app\api\controller;

use app\api\model\Address AS AddressModel;
use app\api\validate\IdMustPositiveInteger;
use app\api\validate\UserIdCheck;
use think\Db;

class Address extends Base
{
    /**
     * 新增收货地址
     * user_id   用户ID
     * username  收货人
     * phone     收货手机号
     * sheng     省ID
     * shi       市ID
     * qu        区ID
     * address   详细地址
     * isDefault  是否默认   1 默认   2 非默认
     * @return \think\response\Json
     */
    public function insertAddress(){
        $user_id = input('user_id');
        $username = input('username');
        $phone = input('phone');
        $sheng = input('sheng');
        $shi = input('shi');
        $qu = input('qu');
        $address = input('address');
        $isDefault = input('isDefault') ? input('isDefault') : 2; // 1 默认   2 非默认

        $resultUserId = (new UserIdCheck())->goCheck();
        if($resultUserId['status'] == 0) return json(['status' => 0, 'msg' => $resultUserId['msg']]);

        $insert = [
            'addr_user_id' => $user_id,
            'addr_username' => $username,
            'addr_phone' => $phone,
            'addr_sheng' => $sheng,
            'addr_shi' => $shi,
            'addr_qu' => $qu,
            'addr_address' => $address,
            'addr_is_default' => $isDefault,
            'addr_time' => createTime()
        ];

        $ADDRESS = new AddressModel();
        $findWhere = [
            'addr_user_id' => $user_id,
            'addr_status' => 1,
            'addr_is_default' => 1
        ];
        $has = $ADDRESS::findAddress($findWhere);
        Db::startTrans();
        try{
            // 将该用户所有收货地址改成非默认
            if($has && $isDefault == 1){
                $updateWhere = ['addr_user_id' => $user_id, 'addr_status' => 1];
                $update = ['addr_is_default' => 2];
                $ADDRESS::updateAddress($updateWhere, $update);
            }

            // 插入收货地址
            $ADDRESS::insertAddress($insert);

            Db::commit();
            return json(['status' => 200, 'msg' => $this->doSuccess]);
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 收货地址列表
     * user_id      用户ID，厂家传0
     * page         页码
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addressList(){
        $user_id = input('user_id'); // 如果是厂家，传0
        $page = input('page') ? input('page') : 1;

        $where = [
            'addr_user_id' => $user_id,
            'addr_status' => 1
        ];
        $field = 'addr_id, addr_username, addr_phone, addr_sheng, addr_shi, addr_qu,
        a1.district sheng, a2.district shi, a3.district qu, addr_address, addr_is_default';

        $ADDRESS = new AddressModel();
        $data = $ADDRESS::selectJoinAddress($where, $field, $page);
        $count = $ADDRESS::countAddress($where);

        if($data){
            return json(['status' => 200, 'msg' => $data, 'count' => $count]);
        }else{
            return json(['status' => 200, 'msg' => [], 'count' => 0]);
        }
    }

    /**
     * 默认收货地址
     * user_id    用户ID，厂家传0
     * type       1 默认收货地址   2 单条收货地址详情
     * addr_id    收货地址ID
     * @return \think\response\Json
     */
    public function addressDetail(){
        $user_id = input('user_id'); // 厂家传0
        $type = input('type') ? input('type') : 1; // 1 默认收货地址   2 单条收货地址详情
        $addr_id = input('addr_id');

        if($type == 1){
            $where = [
                'addr_user_id' => $user_id,
                'addr_status' => 1,
                'addr_is_default' => 1
            ];
        }else{
            $where['addr_id'] = $addr_id;
        }

        $field = 'addr_id, addr_username, addr_phone, addr_sheng, addr_shi, addr_qu,
        a1.district sheng, a2.district shi, a3.district qu, addr_address, addr_is_default';

        $ADDRESS = new AddressModel();
        $data = $ADDRESS::findJoinAddress($where, $field);

        if($data){
            return json(['status' => 200, 'msg' => $data]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 更新收货地址
     * id        收货地址ID
     * user_id   用户ID
     * username  收货人
     * phone     收货手机号
     * sheng     省ID
     * shi       市ID
     * qu        区ID
     * address   详细地址
     * isDefault 是否默认   1 默认   2 非默认
     * @return \think\response\Json
     */
    public function updateAddress(){
        $addr_id = input('id');
        $user_id = input('user_id');
        $username = input('username');
        $phone = input('phone');
        $sheng = input('sheng');
        $shi = input('shi');
        $qu = input('qu');
        $address = input('address');
        $isDefault = input('isDefault') ? input('isDefault') : 2; // 1 默认   2 非默认

        $resultId = (new IdMustPositiveInteger())->goCheck();
        if($resultId['status'] == 0) return json(['status' => 0, 'msg' => $resultId['msg']]);

        $resultUserId = (new UserIdCheck())->goCheck();
        if($resultUserId['status'] == 0) return json(['status' => 0, 'msg' => $resultUserId['msg']]);

        $updateWhere['addr_id'] = $addr_id;
        $update = [
            'addr_username' => $username,
            'addr_phone' => $phone,
            'addr_sheng' => $sheng,
            'addr_shi' => $shi,
            'addr_qu' => $qu,
            'addr_address' => $address,
            'addr_is_default' => $isDefault,
            'addr_update_time' => createTime()
        ];

        $ADDRESS = new AddressModel();

        Db::startTrans();
        try{
            // 将该用户所有收货地址改成非默认
            if($isDefault == 1){
                $findWhere = [
                    'addr_user_id' => $user_id,
                    'addr_status' => 1,
                    'addr_is_default' => 1
                ];
                $has = $ADDRESS::findAddress($findWhere);
                if($has && $has['addr_id'] != $addr_id){
                    $ADDRESS::updateAddress(['addr_id' => $has['addr_id']], ['addr_is_default' => 2]);
                }
            }

            // 更新收货地址
            $ADDRESS::updateAddress($updateWhere, $update);

            Db::commit();
            return json(['status' => 200, 'msg' => $this->doSuccess]);
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }

    }

    /**
     * 设置默认收货地址
     * id      收货地址ID
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function setDefaultAddress(){
        $addr_id = input('id');

        $resultId = (new IdMustPositiveInteger())->goCheck();
        if($resultId['status'] == 0) return json(['status' => 0, 'msg' => $resultId['msg']]);

        $ADDRESS = new AddressModel();

        $_address = $ADDRESS::findAddress(['addr_id' => $addr_id]);
        if($_address['addr_is_default'] == 1){
            return json(['status' => 200, 'msg' => $this->doSuccess]);
        }else{
            Db::startTrans();
            try{
                // 将默认收货地址改成非默认
                $defaultWhere = [
                    'addr_user_id' => $_address['addr_user_id'],
                    'addr_is_default' => 1
                ];
                $defaultUpdate['addr_is_default'] = 2;
                $ADDRESS::updateAddress($defaultWhere, $defaultUpdate);

                // 将操作的收货地址改成默认收货地址
                $where['addr_id'] = $addr_id;
                $update['addr_is_default'] = 1;
                $ADDRESS::updateAddress($where, $update);

                Db::commit();
                return json(['status' => 200, 'msg' => $this->doSuccess]);
            }catch (\Exception $e){
                Db::rollback();
                return json(['status' => 0, 'msg' => $e->getMessage()]);
            }
        }
    }

    /**
     * 删除收货地址
     * id      收货地址ID
     * @return \think\response\Json
     */
    public function delAddress(){
        $addr_id = input('id');

        $resultId = (new IdMustPositiveInteger())->goCheck();
        if($resultId['status'] == 0) return json(['status' => 0, 'msg' => $resultId['msg']]);

        $ADDRESS = new AddressModel();
        $res = $ADDRESS::updateAddress(
            ['addr_id' => $addr_id],
            ['addr_status' => 2, 'addr_update_time' => createTime()]
        );
        if($res){
            return json(['status' => 200, 'msg' => $this->doSuccess]);
        }else{
            return json(['status' => 0, 'msg' => $this->systemErr]);
        }
    }
}